﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace ImageProcessing
{
    public class ImageHelper
    {
        private WriteableBitmap bitmap;
        private byte[] bytes;
        private int height;
        private int width;
        private int multiple;

        public ImageHelper(BitmapSource source)
        {
            bitmap = new WriteableBitmap(source);
            height = source.PixelHeight;
            width = source.PixelWidth;
            multiple = bitmap.Format.BitsPerPixel / 8;
            bytes = new byte[bitmap.PixelHeight * bitmap.PixelWidth * bitmap.Format.BitsPerPixel / 8];
            bitmap.CopyPixels(bytes, bitmap.PixelWidth * bitmap.Format.BitsPerPixel / 8, 0);
        }

        public byte? this[int x, int y, int dimension = 0]
        {
            get
            {
                if (x < 0 || y < 0 || x >= height || y >= width || dimension >= multiple)
                    return null;
                return bytes[(x * width + y) * multiple + dimension];
            }
            set
            {
                if (x < 0 || y < 0 || x >= height || y >= width || dimension >= multiple)
                    return;
                bytes[(x * width + y) * multiple + dimension] = value ?? 0;
            }
        }

        public BitmapSource ToImage()
        {
            WriteableBitmap bitmap2 = new WriteableBitmap(width, height, bitmap.DpiX, bitmap.DpiY, bitmap.Format, bitmap.Palette);
            bitmap2.WritePixels(new System.Windows.Int32Rect(0, 0, bitmap.PixelWidth, bitmap.PixelHeight), bytes, bitmap.PixelWidth * multiple, 0);
            return bitmap2;
        }
    }
}